<template>
    <div class="min-h-screen bg-[#FFFFFF] flex">
      <Nav :disabled="true"></Nav>
      <div class="flex-1 p-8">
        <div class="max-w-3xl mx-auto">
          <!-- 顶部标题区域 -->
          <div class="flex justify-between items-center mb-8">
          <div>
            <h1 class="text-2xl font-medium text-gray-900">添加学生</h1>
            <p  class="text-sm text-gray-500 mt-1">
              请先创建学生账号，才能开始使用学习功能
            </p>
          </div>
        </div>
  
          <!-- 表单卡片 -->
          <div class="bg-white rounded-xl shadow-sm p-8 border border-gray-100">
            <el-form :model="form" label-width="100px" class="max-w-2xl">
              <!-- 头像上传区域 -->
  <div class="flex flex-col items-center mb-12">
    <el-upload
      class="avatar-uploader mb-6"
      action="#"
      :show-file-list="false"
      :auto-upload="false"
      :on-change="handleAvatarChange">
      <div class="relative group">
        <img v-if="avatarUrl || selectedAvatar" 
          :src="avatarUrl || selectedAvatar" 
          class="w-32 h-32 rounded-full object-cover border-4 border-white shadow-lg">
        <div v-else 
          class="w-32 h-32 rounded-full bg-gray-50 border-4 border-white shadow-lg flex items-center justify-center">
          <el-icon class="text-gray-300 text-4xl"><Plus /></el-icon>
        </div>
        <div class="absolute inset-0 bg-black bg-opacity-40 rounded-full opacity-0 group-hover:opacity-100 flex items-center justify-center transition-opacity">
          <span class="text-white text-sm">上传头像</span>
        </div>
      </div>
    </el-upload>
  
    <!-- 操作按钮区域 -->
    <div v-if="selectedAvatar && !avatarUrl" class="flex gap-4">
      <el-button 
        type="primary"
        class="!rounded-full"
        @click="confirmDefaultAvatar">
        <el-icon class="mr-1"><Check /></el-icon>
        确认头像
      </el-button>
      <el-button 
      class="!rounded-full" 
      type="danger" 
        @click="clearSelectedAvatar">
        <el-icon class="mr-1"><Delete /></el-icon>
        清除选择
      </el-button>
    </div>
  
    <!-- 默认头像选择 -->
    <div class="text-sm text-gray-500 mb-4">上传头像或选择默认头像</div>
    <div class="flex gap-4 flex-wrap justify-center">
      <img v-for="(avatar, index) in defaultAvatars" 
        :key="index"
        :src="avatar"
        class="w-16 h-16 rounded-full cursor-pointer border-2 transition-all duration-300 hover:scale-125"
        :class="selectedAvatar === avatar ? 'border-blue-500 scale-110' : 'border-transparent hover:border-gray-200'"
        @click="selectDefaultAvatar(avatar)">
    </div>
  </div>
  
              <!-- 基本信息表单 -->
              <div class="grid grid-cols-2 gap-x-8 gap-y-6">
                <el-form-item label="姓名" required>
                  <el-input v-model="form.username" placeholder="请输入学生姓名" class="!rounded-lg"></el-input>
                </el-form-item>
  
                <el-form-item label="性别" required>
                  <el-radio-group v-model="form.sex">
                    <el-radio label="male" value="1">男生</el-radio>
                    <el-radio label="female" value="2">女生</el-radio>
                  </el-radio-group>
                </el-form-item>
  
                <el-form-item label="年级" required>
                  <el-select v-model="form.grade" placeholder="请选择年级" class="w-full !rounded-lg">
                    <el-option label="一年级" value="1"></el-option>
                    <el-option label="二年级" value="2"></el-option>
                    <el-option label="三年级" value="3"></el-option>
                    <el-option label="四年级" value="4"></el-option>
                    <el-option label="五年级" value="5"></el-option>
                    <el-option label="六年级" value="6"></el-option>
                    <el-option label="小升初" value="6"></el-option>
                  </el-select>
                </el-form-item>
  
                <el-form-item label="教材版本" required>
                  <el-select 
                    v-model="form.version_id" 
                    placeholder="请选择教材版本" 
                    class="w-full !rounded-lg"
                    loading-text="加载中..."
                    :loading="textbooks.length === 0">
                    <el-option 
                      v-for="textbook in textbooks"
                      :key="textbook.value"
                      :label="textbook.label"
                      :value="textbook.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
  
              <!-- 提交按钮区域 -->
              <div class="flex justify-center mt-12 space-x-4">
                <el-button @click="router.back()" 
                  class="w-32 !rounded-full border-gray-300 hover:border-gray-400">
                  取消
                </el-button>
                <el-button type="primary" @click="handleSubmit" 
                  class="w-32 !rounded-full !bg-gradient-to-r from-blue-500 to-blue-600 border-none hover:from-blue-600 hover:to-blue-700">
                  保存
                </el-button>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import Nav from "@/components/nav/index.vue";
  import { ref,onMounted } from 'vue';
  import { Plus, ArrowLeft,Delete,Check } from '@element-plus/icons-vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { addChild} from '@/api/student';
  import { getTextbooks,getGrades } from '@/api/common';  // 教材相关接口
  import { setUserInfo,clearUserInfo } from '@/utils/auth'
  import { userApi } from '@/api'  // 添加这行导入
  import upload from '@/utils/upload';
  
  const router = useRouter();
  const avatarUrl = ref('');
  // 添加selectedAvatar响应式变量
  const selectedAvatar = ref('');
  const imgUrl = import.meta.env.VITE_IMG_BASE_URL;
  
  const form = ref({
    username: '',
    sex: '1',
    grade: '',
    version_id: '',
    avatar_url: ''
  });
  
  
  // 默认头像列表
  const defaultAvatars = [
    new URL('@/assets/images/avatar/10001.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10002.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10003.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10004.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10005.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10006.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10007.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10008.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10009.png', import.meta.url).href,
    new URL('@/assets/images/avatar/10010.png', import.meta.url).href,
  ];
  
  // 修改确认默认头像的方法
  const confirmDefaultAvatar = async () => {
    if (selectedAvatar.value) {
      try {
        // 将URL转换为文件对象
        const response = await fetch(selectedAvatar.value);
        const blob = await response.blob();
        const file = new File([blob], 'avatar.png', { type: blob.type });
  
        // 这里调用上传接口，假设upload.upload方法可以处理URL
        const url = await upload.upload(file, 'image');
  
        avatarUrl.value = imgUrl+url;
        form.value.avatar_url = url;
        selectedAvatar.value = '';
        ElMessage.success('头像设置成功');
      } catch (error) {
        ElMessage.error('头像设置失败');
      }
    }
  };
  
  // 添加清除选择的方法
  const clearSelectedAvatar = () => {
    selectedAvatar.value = '';
  };
  
  const handleAvatarChange = async (file) => {
    try {
      // 如果是默认头像(字符串路径)，直接使用
      if (typeof file === 'string') {
        avatarUrl.value = file;
        form.value.avatar = file;
      } 
      // 如果是上传的文件
      else {
        // 显示预览
        avatarUrl.value = URL.createObjectURL(file.raw);
        // 调用上传接口
        const { url } = await upload.upload(file.raw, 'image');
        avatarUrl.value = imgUrl+url;
        form.value.avatar_url = url;
      }
      console.log(form.value.avatar);
    } catch (error) {
      ElMessage.error('头像设置失败');
      avatarUrl.value = '';
      form.value.avatar = '';
    }
  };
  
  
  const handleSubmit = async () => {
    if (!form.value.username || !form.value.grade || !form.value.version_id) {
      ElMessage.warning('请填写必填项');
      return;
    }
  
    if (!form.value.avatar_url) {
      ElMessage.warning('请上传头像或选择默认头像');
      return;
    }
  
    try {
      const res = await addChild(form.value);

      // 先获取新用户信息
      const userInfo = await userApi.getUserInfo()
      // 清理旧用户信息
      clearUserInfo()
      // 保存新用户信息
      setUserInfo(userInfo)

      // 这里添加实际的提交逻辑
      ElMessage.success('添加成功');
      router.push('/homeFilled');
    } catch (error) {
      ElMessage.error('操作失败，请重试');
    }
  };
  
  const selectDefaultAvatar = (avatar) => {
    selectedAvatar.value = avatar; // 只设置selectedAvatar，不调用handleAvatarChange
  };
  
  const clearAvatar = () => {
    avatarUrl.value = '';
    selectedAvatar.value = '';
    form.value.avatar_url = '';
  };
  
  // 年级和教材版本列表
  // const grades = ref([]);
  // 教材版本列表
  const textbooks = ref([]);
  
  
  
  // 获取等级数据
  // const fetchGrades = async () => {
  //   try {
  //     const res = await getGrades();
  //     return grades.value = res;
  //   } catch (error) {
  //     ElMessage.error('获取年级失败');
  //   }
  // };
  
  // 获取教材版本数据
  const fetchTextbooks = async () => {
    try {
      const res = await getTextbooks();
      return textbooks.value = res.map(item => ({
        label: item.versionName,
        value: item.versionId
      }));
    } catch (error) {
      ElMessage.error('获取教材版本失败');
    }
  };
  
  onMounted(() => {
    // fetchGrades();
    fetchTextbooks(); // 新增教材版本获取
  });
  </script>
  
  <style scoped>
  .avatar-uploader :deep(.el-upload) {
    cursor: pointer;
  }
  
  :deep(.el-input__wrapper),
  :deep(.el-select .el-input__wrapper) {
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) !important;
  }
  
  :deep(.el-input__wrapper:hover),
  :deep(.el-select .el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2) !important;
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
  
  .bg-white {
    transition: box-shadow 0.3s ease;
  }
  
  .bg-white:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  }
  </style>